// 配置相关API
import { axiosInstance } from './request'

// 价格配置工具类
class PriceConfigService {
  static cache = null
  static cacheTime = 0
  static cacheTimeout = 5 * 60 * 1000 // 5分钟缓存

  // 获取价格配置（带缓存）
  static async getPriceConfig() {
    const now = Date.now()
    
    // 如果缓存有效，直接返回
    if (this.cache && (now - this.cacheTime) < this.cacheTimeout) {
      return this.cache
    }
    
    try {
      const response = await axiosInstance.get('/system-config', {
        params: { category: 'price' }
      })
      const configs = response?.data?.configs?.price || []
      
      console.log('获取到的价格配置:', configs)
      
      // 解析配置为对象
      const config = {
        baseRatio: this.getConfigValue(configs, 'base_ratio', 35),
        awmBulletPrice: this.getConfigValue(configs, 'awm_bullet_price', 1.0),
        level6ArmorPrice: this.getConfigValue(configs, 'level6_armor_price', 3.5),
        level6BulletPrice: this.getConfigValue(configs, 'level6_bullet_price', 0.5),
        coffeeBeanPrice: this.getConfigValue(configs, 'coffee_bean_price', 0.8),
        sellRatioDiff: this.getConfigValue(configs, 'sell_ratio_diff', 5)
      }
      
      console.log('解析后的配置对象:', config)
      
      // 更新缓存
      this.cache = config
      this.cacheTime = now
      
      return config
    } catch (error) {
      console.error('获取价格配置失败:', error)
      
      // 如果有旧缓存，返回旧缓存
      if (this.cache) {
        return this.cache
      }
      
      // 返回默认值
      return {
        baseRatio: 35,
        awmBulletPrice: 1.0,
        level6ArmorPrice: 3.5,
        level6BulletPrice: 0.5,
        coffeeBeanPrice: 0.8,
        sellRatioDiff: 5
      }
    }
  }
  
  // 清除缓存
  static clearCache() {
    this.cache = null
    this.cacheTime = 0
  }
  
  // 从配置数组中获取值
  static getConfigValue(configs, key, defaultValue) {
    const config = configs.find(c => c.key === key)
    return config ? Number(config.value) : defaultValue
  }
}

const configAPI = {
  // 获取价格配置参数
  getPriceConfig() {
    return axiosInstance.get('/system-config', {
      params: { category: 'price' }
    })
  }
}

// 导出整个 API 对象和工具类
export default configAPI
export { PriceConfigService }